package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.web.cp.domain.rm.RmobDoubleMerge;
import com.ruoyi.web.mapper.RmobDoubleMergeMapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author xiesm
 * @Description: TODO
 * @date 2025-07-19 16:28
 */
@Service
public class RmobDoubleMergeService {

    @Async
    public void saveRmobDoubleMerge(List<String> games) {
        RmobDoubleMerge rmobMerge = null;
        RmobDoubleMergeService service = SpringUtil.getBean("rmobDoubleMergeService", RmobDoubleMergeService.class);
        for (int i = 0; i < games.size(); i++) {
            String str = games.get(i);
            if (str.startsWith("2025")) {
                String[] strs = str.split(",");
                DateTime date = DateUtil.parse(strs[0], "yyyy-MM-dd HH:mm");

                service.saveOrUpdateByTeamAAndTeamB(rmobMerge);
                rmobMerge = new RmobDoubleMerge(strs[4], date, strs[1], strs[2], strs[3]);
            } else {
                String[] strs = str.split("\\|");
                RmobDoubleMerge.Detail detail = new RmobDoubleMerge.Detail(strs[0], strs[1], strs[2], strs[3],
                        strs[4], strs[5], strs[6], strs[7], strs[8], strs[9], strs[10], strs[11], strs[12]);
                rmobMerge.getDetails().add(detail);
            }
            if (i == (games.size() - 1)) {
                service.saveOrUpdateByTeamAAndTeamB(rmobMerge);
            }
        }
    }

    @Transactional
    public void saveOrUpdateByTeamAAndTeamB(RmobDoubleMerge entity) {
        if (entity == null) {
            return;
        }
        RmobDoubleMergeMapper rmobDoubleMergeMapper = SpringUtil.getBean("rmobDoubleMergeMapper", RmobDoubleMergeMapper.class);
        // 1. 查询是否已存在记录
        RmobDoubleMerge existing = rmobDoubleMergeMapper.selectByGameId(entity.getGameId());
        // 2. 如果存在，设置其 ID 以便更新

        if (existing != null) {
            entity.setId(existing.getId());
            rmobDoubleMergeMapper.updateRmobDoubleMerge(entity);
        } else {
            rmobDoubleMergeMapper.insertRmobDoubleMerge(entity);
        }
    }
}
